<template>
  <el-main>
    <el-card>
      <!-- 更新页面标题样式 -->
      <div class="page-header">
        <div class="page-title">备件管理</div>
        <div class="page-subtitle">设备备件库存管理</div>
      </div>

      <!-- 搜索和筛选 -->
      <el-row :gutter="16" style="margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input v-model="searchText" placeholder="搜索备件名称/规格" clearable />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterCategory" placeholder="全部分类" clearable style="width: 100%;">
            <el-option label="全部分类" value="" />
            <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="全部状态" clearable style="width: 100%;">
            <el-option label="全部状态" value="" />
            <el-option label="正常" value="正常" />
            <el-option label="缺货" value="缺货" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button v-if="userRole === 'admin' || userRole === 'superadmin'" type="primary" @click="showAddDialog = true">添加备件</el-button>
          <el-button type="success" @click="exportExcel">导出Excel</el-button>
        </el-col>
      </el-row>

      <!-- 备件表格 -->
      <el-table :data="filteredSpareParts" border stripe style="width: 100%;">
        <el-table-column prop="name" label="备件名称" width="150" />
        <el-table-column prop="specification" label="规格型号" width="150" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="manufacturer" label="生产厂家" width="120" />
        <el-table-column prop="location" label="存放位置" width="120" />
        <el-table-column prop="stock" label="库存数量" width="100">
          <template #default="scope">
            <span :class="getStockClass(scope.row.stock, 0)">
              {{ scope.row.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="price" label="单价(元)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdate" label="最后更新" width="140" />
        <!-- 被引用设备列，放在操作列前 -->
        <el-table-column label="关联设备" width="220">
          <template #default="scope">
            <div v-if="sparePartDeviceMap[scope.row.objectId] && sparePartDeviceMap[scope.row.objectId].length">
              <el-link
                v-for="dev in sparePartDeviceMap[scope.row.objectId]"
                :key="dev?.objectId || dev?.id || dev"
                type="primary"
                @click.stop="dev && goDeviceDetail(dev)"
              >
                {{ dev?.name || '未知设备' }}{{ dev?.model ? '（' + dev.model + '）' : '' }}
              </el-link>
            </div>
            <span v-else style="color:#bbb;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
                          <el-button v-if="userRole === 'admin' || userRole === 'superadmin'" size="small" @click="editSparePart(scope.row)">编辑</el-button>
              <el-button v-if="userRole === 'admin' || userRole === 'superadmin'" size="small" type="danger" @click="deleteSparePart(scope.row.objectId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin: 20px 0;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredSpareParts.length"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        prev-text="上一页"
        next-text="下一页"
        total-text="共"
        page-size-text="条/页"
        jumper-text="前往"
      />
    </el-card>

    <!-- 添加/编辑备件对话框 -->
          <el-dialog v-if="userRole === 'admin' || userRole === 'superadmin'" v-model="showAddDialog" :title="editingSparePart ? '编辑备件' : '添加备件'" width="600px">
      <el-form :model="sparePartForm" label-width="100px" :rules="rules" ref="formRef">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="备件名称" prop="name">
              <el-input v-model="sparePartForm.name" placeholder="请输入备件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="sparePartForm.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="sparePartForm.category" placeholder="请选择分类" style="width: 100%;">
                <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
                <el-option label="添加新分类" value="__new__" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="sparePartForm.manufacturer" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="存放位置" prop="location">
              <el-select v-model="sparePartForm.location" filterable allow-create default-first-option placeholder="请选择或输入存放位置">
                <el-option v-for="loc in locations" :key="loc" :label="loc" :value="loc" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stock">
              <el-input-number v-model="sparePartForm.stock" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="sparePartForm.unit" placeholder="如：个、件、套" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(元)" prop="price">
              <el-input-number v-model="sparePartForm.price" :min="0" :precision="2" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="sparePartForm.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联设备" prop="relatedDevices">
          <el-select v-model="sparePartForm.relatedDevices" multiple filterable placeholder="请选择关联设备" style="width:100%;">
            <el-option v-for="dev in allDevices" :key="dev.objectId" :label="dev.name + (dev.model ? '（' + dev.model + '）' : '')" :value="dev.objectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="sparePartForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 备件详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="备件详情" width="500px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="备件名称">{{ selectedSparePart.name }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ selectedSparePart.specification }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ selectedSparePart.category }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">{{ selectedSparePart.manufacturer }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">
          <span :class="getStockClass(selectedSparePart.stock, 0)">
            {{ selectedSparePart.stock }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="单位">{{ selectedSparePart.unit }}</el-descriptions-item>
        <el-descriptions-item label="单价">{{ selectedSparePart.price }}元</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ selectedSparePart.supplier }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(selectedSparePart.status)">
            {{ selectedSparePart.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最后更新">{{ selectedSparePart.lastUpdate }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ selectedSparePart.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </el-main>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import AV from '../leancloud'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { ElMessage, ElMessageBox } from 'element-plus'
import locations from '../assets/locations'

// 定义props
const props = defineProps({
  isGuestMode: Boolean
})

// 响应式数据
const spareParts = ref([])
const searchText = ref('')
const filterCategory = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingSparePart = ref(null)
const selectedSparePart = ref({})
const formRef = ref()

// 备件分类
const categories = ref(['机械零件', '电气元件', '传感器', '工具', '耗材', '其他'])

// 加载所有设备并统计引用关系
const allDevices = ref([])
const sparePartDeviceMap = ref({})

// 加载所有设备并统计引用关系
async function fetchAllDevices() {
  const query = new AV.Query('Device')
  query.limit(1000)
  const results = await query.find()
  allDevices.value = results.map(d => d.toJSON())
  // 统计每个备件被哪些设备引用
  const map = {}
  allDevices.value.forEach(dev => {
    if (Array.isArray(dev.spareParts)) {
      dev.spareParts.forEach(sp => {
        const id = typeof sp === 'string' ? sp : sp.objectId
        if (!id) return
        if (!map[id]) map[id] = []
        map[id].push({ objectId: dev.objectId, name: dev.name, model: dev.model })
      })
    }
  })
  sparePartDeviceMap.value = map
}

// 表单数据
const sparePartForm = ref({
  name: '',
  specification: '',
  category: '',
  manufacturer: '',
  location: '', // 新增存放位置
  stock: 0,
  unit: '',
  price: 0,
  supplier: '',
  remark: '',
  relatedDevices: [] // 新增关联设备数组
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入备件名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }]
}

// 计算属性
const filteredSpareParts = computed(() => {
  let result = spareParts.value
  
  if (filterCategory.value) {
    result = result.filter(item => item.category === filterCategory.value)
  }
  
  if (filterStatus.value) {
    result = result.filter(item => item.status === filterStatus.value)
  }
  
  if (searchText.value) {
    const text = searchText.value.toLowerCase()
    result = result.filter(item =>
      item.name?.toLowerCase().includes(text) ||
      item.specification?.toLowerCase().includes(text)
    )
  }
  
  return result
})

// 方法
const fetchSpareParts = async () => {
  try {
    const query = new AV.Query('SparePart')
    query.limit(1000)
    const results = await query.find()
    spareParts.value = results.map(item => {
      const obj = item.toJSON()
      return {
        ...obj,
        lastUpdate: obj.updatedAt ? new Date(obj.updatedAt).toLocaleString() : '',
        status: getStockStatus(obj.stock)
      }
    })
  } catch (error) {
    if (error.message.includes('doesn\'t exists')) {
      spareParts.value = []
      ElMessage.warning('请先在LeanCloud控制台创建SparePart表')
    } else {
      ElMessage.error('获取备件列表失败：' + error.message)
    }
  }
}

const getStockStatus = (stock) => {
  if (stock === 0) return '缺货'
  return '正常'
}

const getStatusType = (status) => {
  const types = {
    '充足': 'success',
    '正常': 'primary',
    '不足': 'warning',
    '缺货': 'danger'
  }
  return types[status] || 'info'
}

const getStockClass = (stock, minStock) => {
  if (stock === 0) return 'stock-empty'
  if (stock <= minStock) return 'stock-low'
  if (stock <= minStock * 2) return 'stock-normal'
  return 'stock-high'
}

const generateSparePartCode = () => {
  const date = new Date();
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  const rand = Math.floor(1000 + Math.random() * 9000);
  return `SP${y}${m}${d}${rand}`;
}

// 1. 顶部按钮
const openAddDialog = () => {
  if (userRole.value !== 'admin' && userRole.value !== 'superadmin') {
    ElMessage.warning('只有管理员才能添加备件')
    return
  }
  editingSparePart.value = null
  resetForm()
  showAddDialog.value = true
}

const editSparePart = (sparePart) => {
  if (userRole.value !== 'admin' && userRole.value !== 'superadmin') {
    ElMessage.warning('只有管理员才能编辑备件')
    return
  }
  editingSparePart.value = sparePart
  Object.assign(sparePartForm.value, sparePart)
  // 统计当前备件被哪些设备关联
  sparePartForm.value.relatedDevices = allDevices.value.filter(dev => Array.isArray(dev.spareParts) && dev.spareParts.some(sp => (sp.objectId || sp.id) === sparePart.objectId)).map(dev => dev.objectId)
  showAddDialog.value = true
}

const viewDetail = (sparePart) => {
  selectedSparePart.value = sparePart
  showDetailDialog.value = true
}

const resetForm = () => {
  sparePartForm.value = {
    name: '',
    specification: '',
    category: '',
    manufacturer: '',
    location: '', // 重置存放位置
    stock: 0,
    unit: '',
    price: 0,
    supplier: '',
    remark: '',
    relatedDevices: [] // 重置关联设备
  }
}

const submitForm = async () => {
  if (userRole.value !== 'admin' && userRole.value !== 'superadmin') {
    ElMessage.warning('只有管理员才能添加/编辑备件')
    return
  }
  try {
    await formRef.value.validate()
    // 自动生成编号
    if (!sparePartForm.value.code) {
      sparePartForm.value.code = generateSparePartCode();
    }
    const SparePart = AV.Object.extend('SparePart')
    let sparePart
    if (editingSparePart.value) {
      sparePart = AV.Object.createWithoutData('SparePart', editingSparePart.value.objectId)
    } else {
      sparePart = new SparePart()
    }
    // 设置字段
    const reservedKeys = ['objectId', 'createdAt', 'updatedAt', 'ACL', 'relatedDevices']
    Object.keys(sparePartForm.value).forEach(key => {
      if (
        !reservedKeys.includes(key) &&
        sparePartForm.value[key] !== undefined &&
        sparePartForm.value[key] !== ''
      ) {
        sparePart.set(key, sparePartForm.value[key])
      }
    })
    // 设置ACL
    const acl = new AV.ACL()
    acl.setPublicReadAccess(true)
    acl.setPublicWriteAccess(true)
    sparePart.setACL(acl)
    await sparePart.save()
    // 处理设备关联
    const relatedIds = sparePartForm.value.relatedDevices || []
    // 先查出所有设备
    const deviceQuery = new AV.Query('Device')
    deviceQuery.limit(1000)
    const allDevs = await deviceQuery.find()
    // 遍历所有设备，更新spareParts字段
    await Promise.all(allDevs.map(async dev => {
      let spList = dev.get('spareParts') || []
      // 移除当前备件
      spList = spList.filter(sp => (sp.objectId || sp.id) !== sparePart.id && (sp.objectId || sp.id) !== sparePart.id && (sp.objectId || sp.id) !== sparePart.objectId)
      // 如果该设备被选中，添加当前备件
      if (relatedIds.includes(dev.id || dev.get('objectId'))) {
        spList.push({ objectId: sparePart.id || sparePart.get('objectId'), name: sparePartForm.value.name, specification: sparePartForm.value.specification, qty: 1 })
      }
      dev.set('spareParts', spList)
      await dev.save()
    }))
    ElMessage.success(editingSparePart.value ? '备件更新成功' : '备件添加成功')
    showAddDialog.value = false
    fetchSpareParts()
    fetchAllDevices()
  } catch (error) {
    if (error.message && error.message.includes('doesn\'t exists')) {
      ElMessage.error('请先在LeanCloud控制台创建SparePart表，或联系管理员')
    } else {
      ElMessage.error('操作失败：' + (error.message || '未知错误'))
    }
  }
}

const deleteSparePart = async (objectId) => {
  if (userRole.value !== 'admin' && userRole.value !== 'superadmin') {
    ElMessage.warning('只有管理员才能删除备件')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除这个备件吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const sparePart = AV.Object.createWithoutData('SparePart', objectId)
    await sparePart.destroy()
    
    ElMessage.success('备件删除成功')
    fetchSpareParts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

const exportExcel = () => {
  const data = filteredSpareParts.value.map(item => ({
    备件名称: item.name,
    规格型号: item.specification,
    分类: item.category,
    生产厂家: item.manufacturer,
    存放位置: item.location,
    库存数量: item.stock,
    单位: item.unit,
    单价: item.price,
    供应商: item.supplier,
    状态: item.status,
    最后更新: item.lastUpdate,
    备注: item.remark
  }))
  
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '备件列表')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '备件列表.xlsx')
}

onMounted(() => {
  fetchSpareParts()
  fetchAllDevices()
})

// 跳转到设备详情
const emit = defineEmits(['go-detail'])
function goDeviceDetail(device) {
  emit('go-detail', device)
}

// 获取用户角色
const userRole = ref(localStorage.getItem('userRole') || 'user')
</script>

<style scoped>
/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

/* 页面标题样式已移至全局样式文件 */

/* 搜索和筛选区域样式 */
.el-row {
  margin-bottom: 20px;
  align-items: center;
}

.el-col {
  display: flex;
  align-items: center;
}

.el-col:last-child {
  justify-content: flex-end;
}

/* 统一按钮样式 */
.header-actions .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.header-actions .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.header-actions .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.header-actions .el-button[type="success"] {
  background: linear-gradient(135deg, #67c23a 0%, #529b2e 100%);
  border: 1px solid #67c23a;
  color: white;
}

.header-actions .el-button[type="success"]:hover {
  background: linear-gradient(135deg, #529b2e 0%, #3f7c23 100%);
  border-color: #529b2e;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.3);
}

/* 表格中的按钮样式 */
.el-table .el-button {
  font-weight: 600;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  gap: 4px;
  height: 28px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-table .el-button[type="danger"] {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  border: 1px solid #f56c6c;
  color: white;
}

.el-table .el-button[type="danger"]:hover {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
  border-color: #e74c3c;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(245, 108, 108, 0.3);
}

/* 对话框中的按钮样式 */
.el-dialog .el-button {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 6px;
  gap: 6px;
  height: 36px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-dialog .el-button[type="primary"] {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: 1px solid #409eff;
  color: white;
}

.el-dialog .el-button[type="primary"]:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
  border-color: #337ecc;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

/* 确保按钮内容居中 */
.el-button .el-button__content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.stock-empty {
  color: #f56c6c;
  font-weight: bold;
}

.stock-low {
  color: #e6a23c;
  font-weight: bold;
}

.stock-normal {
  color: #409eff;
  font-weight: bold;
}

.stock-high {
  color: #67c23a;
  font-weight: bold;
}

@media (max-width: 700px) {
  .el-main {
    padding: 4px !important;
  }
  .page-header {
    text-align: left;
    padding-left: 10px;
    padding-bottom: 5px;
  }
  /* 页面标题样式已移至全局样式文件 */
  .el-row {
    flex-direction: column !important;
    gap: 0;
  }
  .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: 1 1 100%;
  }
  .el-table {
    font-size: 13px;
    min-width: 600px;
    overflow-x: auto;
    display: block;
  }
  .el-table__body-wrapper {
    overflow-x: auto !important;
  }
  .el-button, .el-input, .el-select {
    font-size: 16px !important;
    min-height: 38px !important;
  }
  .el-pagination {
    font-size: 15px;
    padding: 8px 0;
  }
  .el-dialog {
    width: 98vw !important;
    min-width: unset !important;
    max-width: 100vw !important;
    margin: 0 auto;
  }
  .el-form-item__label {
    font-size: 15px !important;
  }
}
</style> 